// pages/mine/onlineShop/onlineShop.js
import api from "../../../common/api.js";
import util from "../../../utils/util.js";
import { getActiveStr } from "../../../utils/utilsNew.js";
let rpx = 1;
// let context = wx.createCanvasContext('share');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banner1: "../images/03.png",
    img1: '../images/001.png',
    img2: '../images/012.png',
    QrCode: '',
    jingjiId: "",
    address: "",
    // imgArray: "https://api.shulanfd.com/aist-filesvr-web/api/files/5a14666bb79945cd8af0613e6befdf2c",
    imgArray: "",
    name: "",
    storeName: "",
    tel: "",
    copyShowDialog: false,
    canvasHidden: true,
  },
  saveImgToPhotosAlbumTap(key, value) {
    wx.getImageInfo({
      src: value,
      success: function (res) {
        //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
        wx.setStorage({
          key: key,
          data: res.path,
        });
      }
    })
  },
  // 分享图片
  share(e,res){
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    that.setData({
      canvasHidden: false
    })
    var banner1 = that.data.banner1;
    var imga = that.data.img1;
    var imgb = that.data.img2;
    var address = that.data.address;
    var imgArray = that.data.imgArray;
    var name = that.data.name;
    // var storeName = that.data.storeName;
    var storeName = that.data.storeName&&that.data.storeName!=' '?that.data.storeName:'--';
    var tel = that.data.tel;
    var qrcodeShop = that.data.QrCode;
    var img1 = '/images/dianhua.png';
    var img2 = '/images/zuobiao.png';
    let context = wx.createCanvasContext('share');
    context.setFillStyle('#e8e8e8');
    context.fillRect(0, 0, 750, 1334);
    context.drawImage(banner1, 0, -100, 750, 700);
    this.roundedRect(context, 45, 550, 660, 710, 20, "#fff");
    this.drawText(context, 40, "#444", name, 250, 595, true)
    this.roundedRect(context, 250, 660, 210, 44, 6, "#ffc800")
    context.setFontSize(24)
    context.setFillStyle("#fff")
    context.drawImage(imga, 260, 665, 30, 30)
    context.fillText('房产资深顾问', 300, 690);
    this.roundedRect(context, 85, 770, 580, 80, 40, "#f6f6f6")
    context.drawImage(imgb, 390-24*storeName.length, 795, 35, 35)
    this.drawText(context, 30, "#444", storeName, 440-24*storeName.length, 793, true)
    context.drawImage(img1, 95, 898, 42, 42)
    context.setFontSize(30)
    context.setFillStyle("#aaa")
    context.fillText(tel, 140, 930);
    context.drawImage(img2, 100, 967, 32, 32)
    context.fillText(address && address != ' ' ? address : '--', 140, 995);
    this.roundedRect(context, 90, 1050, 580, 1, 1, "#ccc")
    this.drawText(context, 30, "#212121", '长按识别二维码', 95, 1090, true)
    context.setFontSize(24)
    context.setFillStyle("#aaa")
    
    context.fillText('可查看我的房源店铺，了解更多', 95, 1170);
    context.fillText('我的房源和我的主营小区', 95, 1210);
    context.drawImage(qrcodeShop, 520, 1070, 160, 160)
    // context.fillRect(45, 250, 660, 700);
    // context.fillRect(0, 0, 750, 1334);
    // context.setFillStyle('#fff');
    // context.setShadow(0, -5, 10, '#ccc')
    // context.fillRect(29, 150, 692, 460);
    // context.setShadow(0, 0, 0, '#fff')
    // context.setFillStyle("#444")
    // context.setFontSize(28)
    // context.fillText(storeName, 64, 220);
    // context.setFillStyle("#444")
    // context.setFontSize(44)
    // context.fillText(name, 64, 290);
    // context.setFontSize(28);
    // context.fillText(tel, 150, 490);
    // address = getActiveStr(address, 30)
    // context.fillText(address && address != ' ' ? address : '--', 150, 540);
    // context.fillText('电话：', 64, 490);
    // context.fillText('地址：', 64, 540);
    // context.setFillStyle("#666")
    // context.fillText('长按识别二维码，查看我的名片', 195, 1150);
    // context.drawImage(qrcodeShop, 250, 830, 260, 260)
    
    wx.downloadFile({
      url: imgArray,
      success: function (rew) {
        context.save()
        context.beginPath()
        // context.arc(600, 285, 65, 0, 2 * Math.PI)
        context.arc(155, 660, 70, 0, 2 * Math.PI)
        context.clip()
        // context.drawImage(rew.tempFilePath, 535, 220,130,130)
        context.drawImage(rew.tempFilePath, 85, 590,140,140)
        context.restore()
  
    context.draw(false, function () {
      setTimeout(function(){
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 750,
        height: 1334,
        destWidth: 750*4,
        destHeight: 1334*4,
        canvasId: 'share',
        success: a => {
          that.shareImgPath = a.tempFilePath,
            that.setData({
              canvasHidden: true
            })
          wx.getImageInfo({
            src: a.tempFilePath,
            success: function (ret) {
              var path = ret.path;
              that.setData({
                copyShowDialog: true,
              })
              wx.hideLoading()
              wx.previewImage({
                urls: [a.tempFilePath]
              })
            }
          })
        },
        fail: e => { console.log('失败') }
        })
      }, 100)
    })
        }
    })
  },
  // 保存图片
  save(e,res){
    wx.showLoading({
      title: '保存中',
    })
    var that = this;
    that.setData({
      canvasHidden: false
    })
    var banner1 = that.data.banner1;
    var imga = that.data.img1;
    var imgb = that.data.img2;
    var address = that.data.address;
    var imgArray = that.data.imgArray;
    var name = that.data.name;
    var storeName = that.data.storeName&&that.data.storeName!=' '?that.data.storeName:'--';
    var tel = that.data.tel;
    var qrcodeShop = that.data.QrCode;
    var img1 = '/images/dianhua.png';
    var img2 = '/images/zuobiao.png';
    let context = wx.createCanvasContext('share');
    context.setFillStyle('#e8e8e8');
    context.fillRect(0, 0, 750, 1334);
    context.drawImage(banner1, 0, -100, 750, 700);
    this.roundedRect(context, 45, 550, 660, 710, 20, "#fff");
    this.drawText(context, 40, "#444", name, 250, 595, true)
    this.roundedRect(context, 250, 660, 210, 44, 6, "#ffc800")
    context.setFontSize(24)
    context.setFillStyle("#fff")
    context.drawImage(imga, 260, 665, 30, 30)
    context.fillText('房产资深顾问', 300, 690);
    this.roundedRect(context, 85, 770, 580, 80, 40, "#f6f6f6")
    context.drawImage(imgb, 390-24*storeName.length, 795, 35, 35)
    this.drawText(context, 30, "#444", storeName, 440-24*storeName.length, 793, true)
    context.drawImage(img1, 95, 898, 42, 42)
    context.setFontSize(30)
    context.setFillStyle("#aaa")
    context.fillText(tel, 140, 930);
    context.drawImage(img2, 100, 967, 32, 32)
    context.fillText(address && address != ' ' ? address : '--', 140, 995);
    this.roundedRect(context, 90, 1050, 580, 1, 1, "#ccc")
    this.drawText(context, 30, "#212121", '长按识别二维码', 95, 1090, true)
    context.setFontSize(24)
    context.setFillStyle("#aaa")
    
    context.fillText('可查看我的房源店铺，了解更多', 95, 1170);
    context.fillText('我的房源和我的主营小区', 95, 1210);
    context.drawImage(qrcodeShop, 520, 1070, 160, 160)

    // context.setFillStyle('#eee');
    // context.fillRect(0, 0, 750, 1334);
    // context.setFillStyle('#fff');
    // context.fillRect(0, 0, 750, 1334);
    // context.setFillStyle('#fff');
    // context.setShadow(0, -5, 10, '#ccc')
    // context.fillRect(29, 150, 692, 460);
    // context.setShadow(0, 0, 0, '#fff')
    // context.setFillStyle("#444")
    // context.setFontSize(28)
    // context.fillText(storeName, 64, 220);
    // context.setFillStyle("#444")
    // context.setFontSize(44)
    // context.fillText(name, 64, 290);
    // context.setFontSize(28);
    // context.fillText(tel, 150, 490);
    // address = getActiveStr(address, 30)
    // context.fillText(address&&address != ' ' ? address:'--', 150, 540);
    // context.fillText('电话：', 64, 490);
    // context.fillText('地址：', 64, 540);
    // context.setFillStyle("#666")
    // context.fillText('长按识别二维码，查看我的名片', 195, 1150);
    // context.drawImage(qrcodeShop, 250, 830, 260, 260)
    wx.downloadFile({
      url: imgArray,
      success: function (rew) {
        context.save()
        context.beginPath()
        context.arc(155, 660, 70, 0, 2 * Math.PI)
        context.clip()
        context.drawImage(rew.tempFilePath, 85, 590,140,140)
        context.restore()
    context.draw(false, function () {
      setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 750,
        height: 1334,
        destWidth: 750*4,
        destHeight: 1334*4,
        canvasId: 'share',
        success: a => {
          that.shareImgPath = a.tempFilePath,
            that.setData({
              canvasHidden: true
            })
          wx.getImageInfo({
            src: a.tempFilePath,
            success: function (ret) {
              var path = ret.path;
              that.setData({
                copyShowDialog: true,
              })
              wx.hideLoading()
              wx.saveImageToPhotosAlbum({
                filePath: path,
                success(result) {
                  wx.showToast({
                    title: '图片已保存',
                  })
                  that.setData({
                    copyShowDialog: true,
                  })
                },
                fail(err){
                  if (!err) return
                  if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                    console.log("当初用户拒绝，再次发起授权")
                    wx.openSetting({
                      success(settingdata) {
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                        } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                        }
                      }
                    })
                  }
                }
              })
              // wx.previewImage({
              //   urls: [a.tempFilePath]
              // })
            }
          })
        },
        fail: e => { console.log('失败') }
      })
      }, 100)
    })
        }
    })
  },
    //绘制圆形图片
    drawCirImage(contex, width, heigth, x, y, img) {
      var contex = contex
      width = Math.floor(width * rpx)
      heigth = Math.floor(heigth * rpx)
      x = Math.floor(x * rpx)
      y = Math.floor(y * rpx)
      var avatarurl_width = width; //绘制的头像宽度
      var avatarurl_heigth = heigth; //绘制的头像高度
      var avatarurl_x = x; //绘制的头像在画布上的位置
      var avatarurl_y = y; //绘制的头像在画布上的位置
      contex.save();
      contex.beginPath(); //开始绘制
      //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
      contex.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
  
      contex.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
  
      contex.drawImage(img, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片，必须是https图片
  
      contex.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    },
      // 绘制圆角矩形带阴影.
  roundedRect(ctx, x, y, width, height, radius, bgColor, shadowBlur) {
    ctx.save()
    x = Math.floor(x * rpx)
    y = Math.floor(y * rpx)
    width = Math.floor(width * rpx)
    height = Math.floor(height * rpx)
    ctx.beginPath();
    ctx.moveTo(x, y + radius);
    ctx.lineTo(x, y + height - radius);
    ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
    ctx.lineTo(x + width - radius, y + height);
    ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
    ctx.lineTo(x + width, y + radius);
    ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
    ctx.lineTo(x + radius, y);
    ctx.quadraticCurveTo(x, y, x, y + radius);
    ctx.setFillStyle(bgColor)
    if (shadowBlur) {
      // 阴影偏移
      ctx.shadowOffsetX = 0;
      ctx.shadowOffsetY = 0;
      // 阴影颜色
      ctx.shadowColor = 'rgba(0,0,0,0.2)';
      // 阴影的模糊半径
      ctx.shadowBlur = 10;
    }
    ctx.fill();
    ctx.restore()
  },

    /** 写文字 */
    drawText(context, fontSize, color, text, x, y, isBold = false) {
      context.save();
      x = Math.floor(x * rpx)
      y = Math.floor(y * rpx + fontSize * rpx)
      fontSize = Math.floor(fontSize * rpx)
      context.setFillStyle(color)
      if (isBold) {
        context.font = `normal bold ${fontSize}px sans-serif`;
      } else {
        context.font = `normal normal ${fontSize}px sans-serif`;
      }
      context.fillText(text, x, y)
      context.restore();
    },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    var loginUserInfo = getApp().globalData.loginUserInfo;
    var user = wx.getStorageSync('user');
    var settingInfo = wx.getStorageSync('settingInfo');
    var jingjiId = {
      agentId: loginUserInfo.data.content.sessionUser.id
    }
    api.qrcodeLongToShort(JSON.stringify(jingjiId), {}, res => {
      let smallCode = res.data.content;
      var QrCode = util.domain + "miniCode/getWXACodeUnlimit?page=" + encodeURI("pages/houseShare/personalShop/personalShop") + "&scene=" + smallCode + "&miniName=zhaofangjs";
      // this.saveImgToPhotosAlbumTap("qrcodeShop", QrCode);
      wx.getImageInfo({
        src: QrCode,
        success: function (res) {
          //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
          // wx.setStorage({
          //   key: key,
          //   data: res.path,
          // });
          // if (options.name) {
          //   that.setData({
          //     QrCode: res.path,
          //     jingjiId: jingjiId,
          //     address: options.address,
          //     imgArray: options.imgArray,
          //     name: options.name,
          //     storeName: options.storeName,
          //     tel: settingInfo.tel ? settingInfo.tel : user.wxMobile,
          //   })
          // } else {
            that.setData({
              QrCode: res.path,
              jingjiId: jingjiId,
              address: settingInfo.address ? settingInfo.address : loginUserInfo.data.content.sessionUser.extProps.storeAdress,
              imgArray: settingInfo.imgArray ? settingInfo.imgArray : loginUserInfo.data.content.sessionUser.avatar,
              name: settingInfo.name ? settingInfo.name : loginUserInfo.data.content.sessionUser.realName,
              storeName: settingInfo.storeName ? settingInfo.storeName : loginUserInfo.data.content.sessionUser.extProps.storeName,
              tel: settingInfo.tel ? settingInfo.tel : loginUserInfo.data.content.sessionUser.mobile
            })
          // }
        }
      })
      // this.saveImgToPhotosAlbumTap("qrcodeShop", QrCode);
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})